#encoding=utf-8
from __future__ import division
import xadmin,ujson,time,datetime,traceback
#新页面不是model对应生成的，菜单url配置中的地址对应register_view的
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, ModelAdminView, CommAdminView, csrf_protect_m
from xadmin.util import unquote
from django.utils.html import escape
from django import forms
from xadmin.layout import Fieldset, Main, Side, Row, FormHelper
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.utils.decorators import method_decorator
from django.http import HttpResponseRedirect
from django.views.decorators.debug import sensitive_post_parameters
from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.db.models import Count, Max, F, Q,Min,Sum
import websys.webconfig as webconfig
import websys.fun as fun
from websys.models import (
    ServerInfo,LogOnline,LogLead,LogBuyItem,LogRecharge,UserInfo,LogLogin,Report_Data
)
from  websys import (
    db_redis
)

import cbyx_userdata
class TestForm(forms.Form):
    """
    A form used to change the password of a user in the admin interface.
    """
    # error_messages = {
    #     'password_mismatch': _("The two password fields didn't match."),
    # }
    # password1 = forms.CharField(label=_("Password"),
    #                             widget=forms.PasswordInput)
    # password2 = forms.CharField(label=_("Password (again)"),
    #                             widget=forms.PasswordInput)

    def __init__(self,  *args, **kwargs):
        #self.user = user
        super(TestForm, self).__init__(*args, **kwargs)

#缓存平台列表
global PFINFO_LIST
PFINFO_LIST=[]#[{'pf_id':'nhmj123','name':'','games':'1,2,3'},...]
def getPlatformInfo_list():
    global PFINFO_LIST
    if not PFINFO_LIST:
        PFINFO_LIST=ServerInfo.objects.all().values('pf',"name")
getPlatformInfo_list()


#print '====================PFINFO_LIST--',PFINFO_LIST
#缓存渠道
global qudao_list

qudao_list={}
not_list=['TEST']
def getqudao_list():
    global qudao_list
    if not qudao_list:
        q_list=UserInfo.objects.values('platform').distinct()
        for q in q_list:
            if str(q['platform']) not in not_list:
                qudao_list[q['platform']]=q['platform']


getqudao_list()


#print '----------------------qudao_list',qudao_list

#url对应的标题
URL2TITLE={'core':'核心数据','online':'在线统计','recharge':'充值统计',
           'props':'道具购买','newloss':'新手流失','loadloss':'加载流失',
           'rank_recharge':'充值排行','blank':'空白页'}
#自定义的页面
URL2DEFINE=['core','online','recharge','props','newloss','loadloss','blank','rank_recharge']

#金钻消耗统计页面
class CommonReportView(ModelAdminView):
    model = ServerInfo
    this_form = TestForm
    common_obj={'jstype':'vendor','css_js':('xadmin.form.css','datepicker.css','xadmin.plugins.css', 'xadmin.page.form.js','xadmin.widget.datetime.js')}
    html_obj={'reportdata/online':{'title':'在线统计','jstype':'static','css_js':('css/jquery-ui.min.css', 'js/jquery-ui.min.js'),'isTemplate':1},
              'reportdata/core':{'title':'核心数据','isTemplate':1},
              'reportdata/recharge':{'title':'充值统计','isTemplate':1},#是否用模板
              'reportdata/newloss':{'title':'新手流失','isTemplate':1},
               'reportdata/loadloss':{'title':'加载流失','isTemplate':1},
              'reportdata/rank_recharge': {'title': '充值排行', 'isTemplate': 1},
              }

    html_obj={}
    for ii in URL2TITLE:
        html_obj[ii]={'title':URL2TITLE[ii]}
        html_obj[ii].update(common_obj)
    #html_obj['share'].update(common_obj)
   # html_obj['table'].update(common_obj)

    # def __init__(self,request):
    #     _title,_tmpurl='金钻消耗统计','diamondreport.html'
    #     self.title=_title
    #     self.tempurl=_tmpurl
    #     print(_title,_tmpurl)

    @csrf_protect_m
    def get(self, request,_type):
        # if not self.has_change_permission(request):
        #     raise 123#PermissionDenied
        self.obj = {}
        self.form = self.this_form()
        #print _type,'--CommonReportView-'
        self.htmlconfig=self.html_obj[_type]
        _title,_tmpurl=self.htmlconfig['title'],'commonreport.html'
        #if 'isDefine' in self.htmlconfig and self.htmlconfig['isDefine']==1:
        if _type in URL2DEFINE:
            _tmpurl='reportdata/%s.html'%(_type)
        self.title=_title

        self.tempurl=_tmpurl
        global PFINFO_LIST
        self.htmldata={'type':_type,'apps':PFINFO_LIST}

        return self.get_response()

    def get_media(self):
        media = super(CommonReportView, self).get_media()
        if self.htmlconfig['jstype']=='static':
            for ii in self.htmlconfig['css_js']:
                file_type = ii.split('.')[-1]
                if file_type=='css':
                    media.add_css({'screen': [ii]})
                elif file_type=='js':
                    media.add_js((self.static(ii),))
            #tmp_media=self.static(*self.htmlconfig['css_js'])
        else:
            media+=self.vendor(*self.htmlconfig['css_js'])
        media = media+ self.form.media
        return media

    def get_context(self):
        #获取数据
        context = super(CommonReportView, self).get_context()
        #print(context,'-------------------*****get_context*****',)
        helper = FormHelper()
        helper.form_tag = False
        self.form.helper = helper
        context.update({
            #'title': _('Change password: %s') % escape(unicode(self.obj)),
            'form': self.form,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_view_permission': True,
            'original': self.obj,
            #chong add
            'title':self.title,#_('My Information'),
            'account_view':True,
            'serverval':"服务器上的值",
            'htmldata':self.htmldata,
            'channel':qudao_list,
        })
        return context

    #可以按不同的参数加载对应的页面
    def get_response(self):
        #print(self.get_context(),"----******get_response*******",self.admin_site.name)
        return TemplateResponse(self.request, [self.tempurl] , self.get_context(), current_app=self.admin_site.name)
        #return TemplateResponse(self.request, [ self.change_user_password_template or'xadmin/auth/user/change_password.html']
                               # , self.get_context(), current_app=self.admin_site.name)

class DiamondReportView(CommonReportView):
    def __init__(self):
        super(DiamondReportView,self)#.__init__('金钻消耗统计','diamondreport.html')

class OnlineReportView(CommonReportView):
    def __init__(self):
        super(OnlineReportView,self)#.__init__('在线统计','onlinereport.html')




#渲染注册请求页面,url配置
# xadmin.site.register_view(r'^core/$', CommonReportView,name='core_report')#核心数据
# xadmin.site.register_view(r'^recharge/$', CommonReportView,name='recharge_report')
# xadmin.site.register_view(r'^online/$', CommonReportView,name='online_report')
# xadmin.site.register_view(r'^props/$', CommonReportView,name='props_report')
# xadmin.site.register_view(r'^newloss/$', CommonReportView,name='newloss_report')
# xadmin.site.register_view(r'^loadloss/$', CommonReportView,name='loadloss_report')
xadmin.site.register_view(r'^reportdata/(.+)/$', CommonReportView,name='user_%s')#各种按日，月，年汇总页面
#ajax请求页面
urlpatterns = patterns('',

                     url(r'^core', 'websys.view.reportdata.op_core', name='op_core'),
                     url(r'^recharge', 'websys.view.reportdata.op_recharge', name='op_recharge'),
                    url(r'^online', 'websys.view.reportdata.op_online', name='op_online'),
                    url(r'^props', 'websys.view.reportdata.op_props', name='op_props'),
                    url(r'^newloss', 'websys.view.reportdata.op_newloss', name='op_newloss'),
                    url(r'^loadloss', 'websys.view.reportdata.op_loadloss', name='op_loadloss'),
                    url(r'^rank_recharge', 'websys.view.reportdata.rank_recharge', name='rank_recharge'),

    )


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_core(request):
    ret =[]

    pfs = request.GET['pf']
    #channel = list(eval(request.GET['channel']))
    channel = str(request.GET['channel'])[:-1].split(',')
    t_date_0, t_date_1 = request.GET["date"].split(',')  # 日期
    t_date_start = time.mktime(time.strptime(str(t_date_0 + ' 00:00:00'), '%Y-%m-%d %H:%M:%S'))
    t_date_end = time.mktime(time.strptime(str(t_date_1 + ' 00:00:00'), '%Y-%m-%d %H:%M:%S'))

    dts_end = datetime.datetime.fromtimestamp(t_date_end)

    end_th_time = dts_end + datetime.timedelta(days=31)

    b_date = t_date_start

    if pfs:
        all_login_num = LogLogin.objects.filter(platform__in=channel,server=pfs).distinct().values('uid').count()
        login_all_info = LogLogin.objects.filter(create_time__gte=t_date_0, create_time__lt=end_th_time,platform__in=channel,server=pfs)

    else:
        all_login_num = LogLogin.objects.filter(platform__in=channel).distinct().values('uid').count()
        login_all_info = LogLogin.objects.filter(create_time__gte=t_date_0, create_time__lt=end_th_time,platform__in=channel)
    while b_date <= t_date_end:

        time_local = time.localtime(b_date)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)

        dts = datetime.datetime.fromtimestamp(b_date)
        delta = datetime.timedelta(days=1)

        changed_time = dts + delta
        add_one = changed_time + delta
        add_two = add_one +delta
        add_seven = dts + datetime.timedelta(days=6)
        add_fourteen = dts + datetime.timedelta(days=13)
        add_thirty = dts + datetime.timedelta(days=29)

        if pfs:
            report_time = Report_Data.objects.filter(create_time__gte=dt, create_time__lt=changed_time,
                                    which_from=pfs).values('create_time',"online_count")  # .distinct()
            online_dict = {0: 0}
            for online_info in report_time:
                k = int(time.mktime(online_info["create_time"].timetuple()) / 600)
                if k not in online_dict:
                    online_dict[k] = online_info["online_count"]
                else:
                    online_dict[k] += online_info["online_count"]

            PCU = max(online_dict.values())
            if sum(online_dict.values())!=0:
                ACU = round(sum(online_dict.values()) / (len(online_dict) - 1), 2)
            else:
                ACU=0

            online_DAU = LogLogin.objects.filter(platform__in=channel,create_time__gte=dt, create_time__lt=changed_time,server=pfs).distinct().values('uid').count()
        else:
            print time.time(), '----------------2---------------------------'
            online_DAU = LogLogin.objects.filter(platform__in=channel,create_time__gte=dt, create_time__lt=changed_time).distinct().values('uid').count()
            print time.time(), '----------------3---------------------------'
            report_time =Report_Data.objects.filter(create_time__gte=dt, create_time__lt=changed_time,which_from__in=channel).values('create_time', "online_count")#.distinct

            online_dict = {0:0}
            for online_info in report_time:
                k = int(time.mktime(online_info["create_time"].timetuple())/600)
                if k not in online_dict:
                    online_dict[k] = online_info["online_count"]
                else:
                    online_dict[k] += online_info["online_count"]

            PCU = max(online_dict.values())
            if sum(online_dict.values())!=0:
                ACU = round(sum(online_dict.values()) / (len(online_dict) - 1), 2)
            else:
                ACU=0

        re_number = 0
        print time.time(), '----------------4---------------------------'
        if pfs:
            new_info = UserInfo.objects.filter(create_time__gte=dt, create_time__lt=changed_time, platform__in=channel,server=pfs)
            #new_user = new_info.count()
            recharge =LogRecharge.objects.filter(platform__in=channel,create_time__gte=dt, create_time__lt=changed_time,server=pfs)
            all_recharge_info_two = LogRecharge.objects.filter(platform__in=channel,create_time__lt=changed_time,server=pfs)
            all_fufei_count =all_recharge_info_two.distinct().values('uid').count()
            for i in recharge.values('money').annotate(moneys=Sum('money')):
                re_number += i['moneys']

        else:
            new_info = UserInfo.objects.filter(create_time__gte=dt, create_time__lt=changed_time, platform__in=channel)
            all_recharge_info_two = LogRecharge.objects.filter(platform__in=channel,create_time__lt=changed_time)
            recharge = LogRecharge.objects.filter(platform__in=channel,create_time__gte=dt, create_time__lt=changed_time)

            all_fufei_count = all_recharge_info_two.distinct().values('uid').count()
            for i in recharge.values('money').annotate(moneys=Sum('money')):
                re_number += i['moneys']

        recharge_count = recharge.distinct().values('uid').count()

        recharge_lv = 0
        ARPPU = 0
        ARPU = 0
        if online_DAU !=0:
            recharge_lv=round(recharge_count / online_DAU,2)
            ARPU = round(re_number / online_DAU,2)
        if recharge_count !=0:
            ARPPU =round(re_number /recharge_count,2)

        re_list = []
        for re in new_info:
            re_list.append(str(re.uid))
        new_user=len(re_list)
        today_num_list=[]
        two_num_list = []
        three_num_list = []
        seven_num_list = []
        fourteen_num_list = []
        thirty_num_list = []
        t_time=datetime.datetime.strptime(dt,"%Y-%m-%d %H:%M:%S")
        print time.time(), '----------------5---------------------------'
        for logins in login_all_info:
            if  t_time<= logins.create_time < changed_time:
                today_num_list.append(str(logins.uid))
            if changed_time <= logins.create_time < add_one:
                two_num_list.append(str(logins.uid))
            if (add_one) <= logins.create_time < add_two:
                three_num_list.append(str(logins.uid))
            if add_seven <= logins.create_time< add_seven +delta :
                seven_num_list.append(str(logins.uid))
            if add_fourteen <= logins.create_time < add_fourteen +delta :
                fourteen_num_list.append(str(logins.uid))
            if add_thirty <= logins.create_time < add_thirty+delta :
                thirty_num_list.append(str(logins.uid))
        n_t_list=set(today_num_list)
        today_num = len(set(re_list) &n_t_list)
        two_num = len((set(two_num_list)&(set(re_list))))
        three_num = len((set(three_num_list)&(set(re_list))))
        seven_num = len((set(seven_num_list)&(set(re_list))))
        fourteen_num = len((set(fourteen_num_list)&(set(re_list))))
        thirty_num = len((set(thirty_num_list)&(set(re_list))))
        print time.time(), '----------------6---------------------------'
        D2RR = 0
        D3RR=0
        D7RR = 0
        D14RR = 0
        D30RR = 0
        if today_num !=0:
            D2RR =round(two_num /today_num,4)
            D3RR = round(three_num / today_num,4)
            D7RR = round(seven_num / today_num,4)
            D14RR = round(fourteen_num / today_num,4)
            D30RR = round(thirty_num / today_num,4)

        all_re_num = 0
        for re_num in all_recharge_info_two.values('money').annotate(moneys=Sum('money')):
            all_re_num +=re_num['moneys']

        all_buy_lv = 0
        if all_login_num !=0:
            all_buy_lv = round(all_fufei_count / all_login_num,2)
        info_dic = {}
        info_dic['datess'] = dt.split(' ')[0]
        info_dic['dau'] = online_DAU
        info_dic['newuser'] = new_user
        info_dic['pcu'] =PCU
        info_dic['acu'] = ACU
        info_dic['recharge'] = re_number
        info_dic['payrate'] = "%.2f%%" %(recharge_lv * 100)
        info_dic['arppu'] = ARPPU
        info_dic['t_arpu'] = ARPU
        info_dic['allpaycount'] = all_fufei_count
        info_dic['allrecharge'] = all_re_num
        info_dic['allpayrate'] = "%.2f%%" %(all_buy_lv * 100)
        info_dic['d1rr'] = today_num
        info_dic['d2rr'] = "%.2f%%" %(D2RR * 100)
        info_dic['d3rr'] = "%.2f%%" %(D3RR * 100)
        info_dic['d7rr'] = "%.2f%%" %(D7RR * 100)
        info_dic['d14rr'] = "%.2f%%" %(D14RR * 100)
        info_dic['d30rr'] = "%.2f%%" %(D30RR * 100)
        ret.append(info_dic)
        Unixtime = time.mktime(time.strptime(changed_time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S'))
        b_date = Unixtime
        print time.time(), '----------------7---------------------------'
    ret.reverse()
    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_recharge(request):
    t_date_0, t_date_1 = request.GET["date"].split(',')  # 日期
    s_id = request.GET["pf"]  # 服
    channel = str(request.GET['channel']).split(',')
    #print channel,'-----------------ccccccccccc---------------'
    t_date_start = t_date_0 + ' 00:00:00'
    t_date_end = t_date_1 + ' 23:00:00'
    recharge = LogRecharge.objects.filter(create_time__range=(t_date_start,t_date_end),platform__in=channel).order_by('-create_time')
    lists=[]
    if s_id:
        recharge=recharge.filter(server=s_id)
    for i in recharge:
        if not UserInfo.objects.filter(uid=i.uid).exists():
            continue
        uid_info = UserInfo.objects.get(uid=i.uid)
        uid_dic={}
        uid_dic['uid']=uid_info.uid
        uid_dic['nick']=uid_info.username
        uid_dic['recharge']=i.money
        uid_dic['retime']=str(i.create_time)
        lists.append(uid_dic)
    return HttpResponse(ujson.dumps(lists))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_online(request):
    #time111=time.time()
    #ret = [{'la_acu':2,'la_pcu':3,'hour':7,'count':8},{'la_acu':2,'la_pcu':3,'hour':10,'count':9}]
    data={'code':-1,'msg':'','datas':{'today':[],'before':[]},'max':0}
    #参数
    #t_date=request.GET["date"]
    s_id = request.POST["pf"]#服
    channel=[]
    all_channel=False
    if str(request.POST['channel[]'])=='all':
        all_channel=True
    else:
        channel = str(request.POST['channel[]']).split(',')
    #查询数据
    t_date_start = time.mktime(time.strptime(time.strftime('%Y-%m-%d 00:00:00'), '%Y-%m-%d %H:%M:%S'))
    #t_date_start = time.mktime(time.strptime('2017-12-06 00:00:00', '%Y-%m-%d %H:%M:%S'))
    t_date_center=datetime.datetime.fromtimestamp(t_date_start)
    one_day=datetime.timedelta(days=1)
    t_date_end=t_date_center +one_day
    t_date_before=t_date_center - one_day

    time_now=time.mktime(time.strptime(time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S'))
    time_now=datetime.datetime.fromtimestamp(time_now)
    five_minute=datetime.timedelta(minutes=5)
    five_minute_ago=time_now - five_minute
    online_now_number=LogOnline.objects.filter(create_time__gte=five_minute_ago, create_time__lt=
    time.strftime('%Y-%m-%d %H:%M:%S')).distinct().values('uid').count()

    # thirty_days=datetime.timedelta(days=30)
    # thirty_days_ago=t_date_center - thirty_days
    #
    # thirty_days_ago=time.mktime(time.strptime(thirty_days_ago.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S'))
    #
    # b_date = thirty_days_ago
    #
    # thirty_online_list=[0,]

    #print time.time(), '-----------time---------1-----------'

    # while b_date<=t_date_start:
    #     time_local = time.localtime(b_date)
    #     dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
    #     dts = datetime.datetime.fromtimestamp(b_date)
    #     delta = datetime.timedelta(days=1)
    #
    #     changed_time = dts + delta
    #     days_online = LogOnline.objects.filter(create_time__gte=dt, create_time__lt=changed_time).distinct().order_by().values('uid').count()  # group by time
    #     thirty_online_list.append(days_online)
    #     Unixtime = time.mktime(time.strptime(changed_time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S'))
    #     b_date = Unixtime


    #print time.time(),'-----------time---------2-----------'


    for num in range(1,3):
        ret=[]
        if num==1:
            date1=t_date_center
            date2=t_date_end
        else:
            date1 = t_date_before
            date2 = t_date_center
        # if all_channel:
        #     #print date1,'-<<---------------',date2
        #     lo_arr = LogOnline.objects.filter(create_time__gte=date1, create_time__lt=date2)  # group by time
        #     #print '=================',lo_arr
        # else:
        #     strs = 'Q(platform="test")'
        #     for plat in channel:
        #         strs += ' | '
        #         strs +='Q(platform="%s")'%str(plat)
        #     lo_arr = LogOnline.objects.filter(create_time__gte=date1, create_time__lt=date2).filter(eval(strs)) # group by time
        #
        # if str(s_id)!='all':
        #     lo_arr = lo_arr.filter(server=s_id)  # group by time
        lo_arr = LogOnline.objects.filter(create_time__gte=date1, create_time__lt=date2)  # group by time
        item_dic = {}

        # for ii_item in lo_arr:
        #     num_dic = {'uid': [], 'num': 0}
        #     hour_time=datetime.datetime.strftime(ii_item.create_time,'%H')
        #     if hour_time not in item_dic:
        #         num_dic['uid'].append(ii_item.uid)
        #         num_dic['num'] =num_dic['num'] +1
        #         item_dic[hour_time]=num_dic
        #     else:
        #         if ii_item.uid not in item_dic[hour_time]['uid']:
        #             item_dic[hour_time]['uid'].append(ii_item.uid)
        #             item_dic[hour_time]['num'] +=1

        for ii_item in lo_arr:
            if all_channel:
                if str(s_id)!='all':
                    if ii_item.server == str(s_id):
                        num_dic = {'uid': [], 'num': 0}
                        hour_time=datetime.datetime.strftime(ii_item.create_time,'%H')
                        if hour_time not in item_dic:
                            num_dic['uid'].append(ii_item.uid)
                            num_dic['num'] =num_dic['num'] +1
                            item_dic[hour_time]=num_dic
                        else:
                            if ii_item.uid not in item_dic[hour_time]['uid']:
                                item_dic[hour_time]['uid'].append(ii_item.uid)
                                item_dic[hour_time]['num'] +=1
                else:
                    num_dic = {'uid': [], 'num': 0}
                    hour_time = datetime.datetime.strftime(ii_item.create_time, '%H')
                    if hour_time not in item_dic:
                        num_dic['uid'].append(ii_item.uid)
                        num_dic['num'] = num_dic['num'] + 1
                        item_dic[hour_time] = num_dic
                    else:
                        if ii_item.uid not in item_dic[hour_time]['uid']:
                            item_dic[hour_time]['uid'].append(ii_item.uid)
                            item_dic[hour_time]['num'] += 1
            else:
                if str(ii_item.platform) in channel:
                    if str(s_id) != 'all':
                        if ii_item.server == str(s_id):
                            num_dic = {'uid': [], 'num': 0}
                            hour_time = datetime.datetime.strftime(ii_item.create_time, '%H')
                            if hour_time not in item_dic:
                                num_dic['uid'].append(ii_item.uid)
                                num_dic['num'] = num_dic['num'] + 1
                                item_dic[hour_time] = num_dic
                            else:
                                if ii_item.uid not in item_dic[hour_time]['uid']:
                                    item_dic[hour_time]['uid'].append(ii_item.uid)
                                    item_dic[hour_time]['num'] += 1
                    else:
                        num_dic = {'uid': [], 'num': 0}
                        hour_time = datetime.datetime.strftime(ii_item.create_time, '%H')
                        if hour_time not in item_dic:
                            num_dic['uid'].append(ii_item.uid)
                            num_dic['num'] = num_dic['num'] + 1
                            item_dic[hour_time] = num_dic
                        else:
                            if ii_item.uid not in item_dic[hour_time]['uid']:
                                item_dic[hour_time]['uid'].append(ii_item.uid)
                                item_dic[hour_time]['num'] += 1
        for i in item_dic:
            ret.append({'hour':i, 'count':item_dic[i]['num']})
        time_list=['00','01','02','03','04','05','06','07','08','09','10','11',
                   '12','13','14','15','16','17','18','19','20','21','22','23']
        hour_lists=[]
        for time_info in ret:
            #print time_info,'-----------------timeinfo'
            hour_lists.append(time_info.values()[1])
        for hour in time_list:
            if hour not in hour_lists:
                ret.append({'hour': hour, 'count': 0})
        from operator import itemgetter
        #ret.sort(key = lambda x:x["hour"])
        ret.sort(key=itemgetter('hour'))
        #print ret,'--------reew---------------'

        if num==1:
            for j in ret:
                data['datas']['today'].append(j['count'])
        else:
            for j in ret:
                data['datas']['before'].append(j['count'])
    #print time.time(), '-----------time---------3-----------'
    if data['datas']['today']!=[]:
        data['max']=int(max(data['datas']['today']))
        if data['datas']['before']!=[]:
            if data['max'] < max(data['datas']['before']):
                data['max'] = int(max(data['datas']['before']))
    if 0<=data['max'] <50:
        data['max'] += 10
    elif 50<=data['max']<100:
        data['max'] +=30
    elif 100<=data['max']<500:
        data['max'] += 150
    elif 500<=data['max']<1000:
        data['max'] += 250
    elif 1000<=data['max'] <2000:
        data['max'] +=350
    else:
        data['max'] += 500
    if data['datas']['today']==[]:
        data['datas']['today']=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    if data['datas']['before']==[]:
        data['datas']['before']=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    #print time.time(),'-----------time---------5-----------'
    data['online_count']=online_now_number
    # data['thirty_online']=max(thirty_online_list)
    data['code']=0
    data['msg']='success'
    #time222=time.time()
    print data['datas']['before'],'--------=-=-=-=-=-=-=',s_id
    return HttpResponse(ujson.dumps(data))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_props(request):
    # ret = [{'id':2,'name':3,'amount_today':7,'amount_yestoday':8,'amount_trend':2,'amount_average':3,'people_today':7,'people_yestoday':8,'people_trend':2,'people_average':3,'income_today':10,'income_yestoday':9,'income_trend':35,'income_average':88},
    #        {'id': 2, 'name': 3, 'amount_today': 7, 'amount_yestoday': 8, 'amount_trend': 2, 'amount_average': 3,
    #         'people_today': 7, 'people_yestoday': 8, 'people_trend': 2, 'people_average': 3, 'income_today': 10,
    #         'income_yestoday': 9, 'income_trend': 35, 'income_average': 88}]
    ret=[]
    #参数
    t_date_0,t_date_1=request.GET["date"].split(',')#日期
    s_id = request.GET["pf"]#服
    t_id = request.GET["tid"]#道具id
    #print request.GET.dict(),'--------1----------------'
    channel = str(request.GET['channel']).split(',')
    #print channel,'=========',s_id
    #查询数据
    t_filter=LogBuyItem.objects.filter(platform__in=channel,create_time__range=(t_date_0+' 00:00:00',t_date_1+' 23:59:59'))
    if s_id:
        t_filter=t_filter.filter(server=s_id)
    if t_id!='':
        t_filter=t_filter.filter(buy_id=t_id)
    print t_filter,'------------'
    t_arr=t_filter.values('buy_id','reason').annotate(count=Count('uid',distinct=True),num=Sum('num'),amt=Sum('amt'),)#group by buy_id
    for ii_item in t_arr:
        tmp_obj={'id':ii_item['buy_id'],'reason':ii_item['reason'],'count':ii_item['count'],'num':ii_item['num'],'amt':ii_item['amt']}
        datas=cbyx_userdata.getjs('store')
        if tmp_obj['reason']=='SHOP_BUY':
            names_item=datas['SHOP_INFO'][tmp_obj['id']]['item_name']
        else:
            names_item = datas['VIP_SHOP_INFO'][tmp_obj['id']]['item_name']
        tmp_obj['item_name']=names_item
        ret.append(tmp_obj)
    #按数量排序,reverse=True
    ret.sort(key = lambda x:x["num"],reverse=True)
    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_newloss(request):


    ret = [{'lead_step':1,'hit_count':2,'loss_count':3,'loss_rate':4,'lead_remain':5},{'lead_step':1,'hit_count':2,'loss_count':3,'loss_rate':4,'lead_remain':5}]
    ret=[]
    #参数
    t_date_0,t_date_1=request.GET["date"].split(',')
    s_id = request.GET["pf"]#服
    channel = str(request.GET['channel']).split(',')
    print channel,'-------------'
    #查询数据
    t_arr=LogLead.objects.filter(platform__in=channel,create_date__range=(t_date_0,t_date_1))
    if s_id:
        t_arr=t_arr.filter(server=s_id)
    stage_obj={}#阶级对应的数值
    stage_user={}#阶级值的玩家
    for ii_item in t_arr:
        ii_stage=int(ii_item.stage)
        ii_step=ii_item.step
        ii_uid =ii_item.uid
        if ii_stage not in stage_obj:
            stage_obj[ii_stage]=ii_stage
            stage_user[ii_stage]=1
        else:
            stage_user[ii_stage]+=1
    #点击人数
    print stage_obj,'---------',stage_user
    tmp_arr=stage_obj.keys()
    tmp_arr.sort()
    hit_obj={}
    tmp_len=len(tmp_arr)
    for ii in range(tmp_len):
        tmp_num=0
        for jj in range(ii,tmp_len):
            tmp_step=tmp_arr[jj]
            tmp_num+=stage_user[tmp_step]
        hit_obj[tmp_arr[ii]]=tmp_num
    #生成数据
    for ii in range(tmp_len):
        tmp_step=tmp_arr[ii]
        tmp_obj={'lead_step':stage_obj[tmp_step],'hit_count':hit_obj[tmp_step],'loss_count':stage_user[tmp_step],'loss_rate':0}
        if tmp_step==100:#已经完成的
            tmp_obj['loss_count']=0
        if tmp_obj['loss_count']>0:
            tmp_obj['loss_rate']=round(float(tmp_obj['loss_count'])/tmp_obj['hit_count'],2)
        ret.append(tmp_obj)
    ret.sort(key=lambda x: x["lead_step"])
    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_loadloss(request):
    ret = [{'lead_step':1,'hit_count':2,'loss_count':3,'loss_rate':4},{'lead_step':1,'hit_count':2,'loss_count':3,'loss_rate':4}]
    return HttpResponse(ujson.dumps(ret))





#充值排行
@csrf_exempt
@login_required(login_url="/xadmin/")
def rank_recharge(request):
    t_date_0, t_date_1 = request.GET["date"].split(',')  # 日期
    s_id = request.GET["pf"]  # 服
    is_all_date=request.GET['isall_date[]']
    #print request.GET.dict(),'---------------1sssss----'
    channel=[]
    all_channel=False
    if str(request.GET['channel'])=='all':
        all_channel=True
    else:
        channel = str(request.GET['channel']).split(',')
    t_date_start = t_date_0 + ' 00:00:00'
    t_date_end = t_date_1 + ' 23:00:00'
    if str(is_all_date)=='1':
        t_date_start='2017-12-05 00:00:00'
        t_date_end = time.strftime('%Y-%m-%d 00:00:00')
    #print t_date_start,'-----------------sss',t_date_end
    #print '----------------->>1',channel
    if all_channel:
        recharge = LogRecharge.objects.filter(create_time__range=(t_date_start, t_date_end))\
        .values('uid').annotate(moneys=Sum('money'))
    else:
        recharge = LogRecharge.objects.filter(create_time__range=(t_date_start, t_date_end),platform__in=channel)\
        .values('uid').annotate(moneys=Sum('money'))

    if str(s_id)!='all':
        recharge=recharge.filter(server=str(s_id))
    recharge=recharge.order_by('-moneys')[:50]
    lists=[]
    rank=1
    #print  len(recharge),'-------------lenths'
    for i in recharge:
        if not UserInfo.objects.filter(uid=i['uid']).exists():
            continue
        uid_info = UserInfo.objects.get(uid=i['uid'])
        #online_time=str(LogOnline.objects.filter(uid=i['uid']).order_by('-create_time')[0].create_time)
        u_dicts={}
        u_dicts['rank']=rank
        u_dicts['nick']=uid_info.username
        u_dicts['recharge']=i['moneys']
        u_dicts['retime']=str(uid_info.create_time)
        u_dicts['online_time']=str(uid_info.recently_online)
        lists.append(u_dicts)
        rank+=1
    print '----------------->>3',time.time()
    return HttpResponse(ujson.dumps(lists))
